import process from 'process'
import path from 'path'
import fs from 'fs'

export class IParams {
    pipelineID!: number

    pipelineName!: string

    buildNumber?: number

    workSpace!: string

    projectDir!: string

    buildJobID!: number

    pluginDir!: string

    useLocalRules!: boolean

    localDependencies!: string

    incrementalScan!:boolean

    exclusion!: string

    redline!: string

    stepIdentifier!: string

    nodeVersion!: string

    getPluginDir = () => {
        if (process.env.PLUGIN_DIR){
            return process.env.PLUGIN_DIR
        }
        if (process.env.HOME === undefined){
            throw new Error('HOME is not set')
        }
        const pluginDir = path.join(process.env.HOME as string, 'plugins')
        if (!fs.existsSync(pluginDir)) {
            fs.mkdirSync(pluginDir)
        }
        return pluginDir
    }
}

export function getParams(): IParams {
    let params = new IParams()
    params.pipelineID = Number(process.env.PIPELINE_ID)
    params.pipelineName = process.env.PIPELINE_NAME as string
    params.buildNumber = Number(process.env.BUILD_NUMBER)
    params.workSpace = process.env.WORK_SPACE as string
    params.projectDir = process.env.PROJECT_DIR as string
    params.buildJobID = Number(process.env.BUILD_JOB_ID)
    params.pluginDir = params.getPluginDir()
    params.useLocalRules = process.env.USE_LOCAL_RULES === 'true'
    params.localDependencies = process.env.USE_LOCAL_DEPENDENCIES || ""
    params.incrementalScan = process.env.INCREASE === 'true'
    params.exclusion = process.env.EXCLUSION || ""
    params.redline = process.env.CHECK_REDLINES || "[]"
    params.stepIdentifier = process.env.stepIdentifier as string
    params.nodeVersion = process.env.CI_RUNTIME_VERSION as string
    return params
}